package com.quzitech.efest.activitys.main;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.quzitech.efest.R;
import com.quzitech.efest.activitys.myConstants;
import com.quzitech.efest.activitys.base.ActivityManager;
import com.quzitech.efest.activitys.base.BaseApplication;
import com.quzitech.efest.activitys.base.ViewInject;
import com.quzitech.efest.activitys.ble.ConnectedLeDevice;
import com.quzitech.efest.activitys.device.DeviceActivity;
import com.quzitech.efest.activitys.slidedrawer.AboutActivity;
import com.quzitech.efest.activitys.slidedrawer.ScanQRCode;
import com.quzitech.efest.handle.IDialogGuide;
import com.quzitech.efest.handle.IDiaolgHandler;
import com.quzitech.efest.handle.ISlotCurrentTypeHandler;
import com.quzitech.efest.handle.NoDoubleClickListener;
import com.quzitech.efest.protocol.ConCreteCmd;
import com.quzitech.efest.protocol.ConCreteCmd.IPASS;
import com.quzitech.efest.protocol.ConCreteCmd.ITYPE;
import com.quzitech.efest.protocol.MyRequest;
import com.quzitech.efest.protocol.MyRespose;
import com.quzitech.efest.protocol.ResponseCmd;
import com.quzitech.efest.protocol.ResponseCmd.IRESTYPE;
import com.quzitech.efest.protocol.StringUtil;
import com.quzitech.efest.utils.CmdLoopThread;
import com.quzitech.efest.utils.DialogUtil;
import com.quzitech.efest.utils.GuideUtil;
import com.quzitech.efest.utils.HexUtil;
import com.quzitech.efest.utils.IfSupUtil;
import com.quzitech.efest.utils.InitChartXYlist;
import com.quzitech.efest.utils.MacUtil;
import com.quzitech.efest.utils.MyDateUtils;
import com.quzitech.efest.utils.Myutil;
import com.quzitech.efest.utils.NoDoubleClickUtil;
import com.quzitech.efest.utils.SetBatteryParmUtil;
import com.quzitech.efest.utils.getBatteryReminderParamUtil;
import com.quzitech.efest.utils.getVTUtil;
import com.quzitech.efest.utils.transferuti;
import com.quzitech.efest.view.BatteryAmount;
import com.quzitech.efest.view.MyDialog;
import com.quzitech.efest.view.MyDialogGuide;
import com.quzitech.efest.view.SlotCurrentType;
import com.quzitech.efest.view.SlotCurrentTypeUtil;
import com.quzitech.efest.view.TitleBar;
import com.quzitech.efest.view.chart.LineView;
import com.tuner168.api.DataUtil;

public class MainActivity extends MainFunction {
	// --------------------------------
	@ViewInject(id = R.id.ba_main_second)
	BatteryAmount ba_main_second;
	@ViewInject(id = R.id.linear_main_second)
	private LinearLayout linear_main_second;
	@ViewInject(id = R.id.sct_main_second)
	private SlotCurrentType sct_main_second;
	@ViewInject(id = R.id.view_percomchart_Xdate)
	private LineView view_percomchart_Xdate;
	@ViewInject(id = R.id.tb_slot_chargecap)
	private TextView tb_slot_chargecap;
	@ViewInject(id = R.id.tb_slot_title)
	private TextView tb_slot_title;

	// -------------------------------

	@ViewInject(id = R.id.sv_main_first)
	ScrollView sv_main_first;
	@ViewInject(id = R.id.tb_main)
	TitleBar tb_main;
	private ImageView mCollectView;
	@ViewInject(id = R.id.main_drawerlayout)
	private DrawerLayout drawerLayout;
	@ViewInject(id = R.id.main_left)
	private LinearLayout slidemenu;

	@ViewInject(id = R.id.linear_main_slide_productverify)
	private LinearLayout linear_main_slide_productverify;
	@ViewInject(id = R.id.linear_main_slide_help)
	private LinearLayout linear_main_slide_help;
	@ViewInject(id = R.id.linear_main_slide_about)
	private LinearLayout linear_main_slide_about;
	@ViewInject(id = R.id.linear_main_slide_store)
	private LinearLayout linear_main_slide_store;

	@ViewInject(id = R.id.ba_main_ba1)
	private BatteryAmount ba_main_ba1;
	@ViewInject(id = R.id.ba_main_ba2)
	private BatteryAmount ba_main_ba2;
	@ViewInject(id = R.id.ba_main_ba3)
	private BatteryAmount ba_main_ba3;
	@ViewInject(id = R.id.ba_main_ba4)
	private BatteryAmount ba_main_ba4;

	// @ViewInject(id = R.id.tb_main_togglebutton)
	// private ToggleButton tb_main_togglebutton;
	@ViewInject(id = R.id.iv_main_screen)
	private ImageView iv_main_screen;

	private boolean isScreenOn = false;
	// int randomint = 8;
	private static final int MAINVIEW = 0;
	private static final int SLOTVIEW = 1;
	private static int CurrentView = 0;
	private int SlotNo = 0;

	Handler handler;
	private final static int NOTIFY_DATA = 1;
	private final static int CONNECTED = 2;
	private final static int IF_VT_ENOUGH = 3;
	private final static int TIME = 4;
	private final static int DISCOVERY = 5;
	private final static int DISCONNECTED = 6;
	private final static int DIALOGTIMEOUT = 7;
	private final static int SHOWDIALOG = 8;
	private final static int CONNECT_TIMEOUT = 9;
	private final static int OBTAIN_DATA = 99;

	private static ArrayList<Integer> vtlist = new ArrayList<Integer>();
	private static List<Double> ylist = new ArrayList<Double>();
	ArrayList<Integer> dataList2 = new ArrayList<Integer>();
	ArrayList<ArrayList<Integer>> dataLists = new ArrayList<ArrayList<Integer>>();
	ArrayList<Integer> dataList = new ArrayList<Integer>();
	CmdLoopThread r = null;
	boolean IFHAVELUNXUN = false;
	Thread t = null;
	int vtcount = 0;
	private Handler mHandler = new Handler();
	private boolean mScanning = false;
	private int SCAN_PERIOD = 5000;
	byte[] receive_data;

	public interface ViEW_MAIN {

		int MAIN = MAINVIEW;

		int SLOT = SLOTVIEW;

	}

	@Override
	protected int getlayout() {

		return R.layout.layout_main;
	}

	@Override
	public void onClick(View v) {

		super.onClick(v);
		switch (v.getId()) {
		case R.id.linear_main_slide_productverify:
			nextActivity(ScanQRCode.class);
			break;
		case R.id.linear_main_slide_help:
			// ToastMsg_short("help");
			// GuideUtil.saveMainGuide(getApplicationContext(), ifneed);'
			GuideUtil.initAll(getApplicationContext());
			drawerLayout.closeDrawers();
			break;
		case R.id.linear_main_slide_about:
			nextActivity(AboutActivity.class);
			break;
		case R.id.linear_main_slide_store:

			Myutil.SearchUrl(
					getResources().getString(R.string.main_slide_amazonstore),
					getApplicationContext());
			break;
		default:
			break;
		}
	}

	@Override
	protected void initData() {

		initHandler();
		initBroadcastReceiver();
		initTitleBarMain();
		initSlideDrawer();
		setDrawlister();
		initBatteryMain();
		initScreenStatus();
		ifSupportBle();
		initNotifiManager();
		regBroadcast();
		startConnectBack();

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (myConstants.IFCONNECTED) {
			mCollectView.setImageResource(R.drawable.bluetoothon);

		}
		checkConnectedDevice();
		obtainDataThread();

		if (GuideUtil.getMainGuide(getApplicationContext())) {
			GuideUtil.saveMainGuide(getApplicationContext(), false);
			showMainGuide();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregBroadcast();
		t.stop();
		t = null;
		r = null;
	}

	@Override
	protected void onStop() {
		super.onStop();

	}

	/**
	 * ��ʼ����������
	 */
	private void initBatteryMain() {

		ba_main_ba1.setNoBattery(1);

		ba_main_ba1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ba_main_ba1.getIFHaveBattery()) {
					SlotNo = 1;
					nextAccordingCurrentView(ViEW_MAIN.SLOT);
				}

			}
		});
		ba_main_ba2.setNoBattery(2);
		ba_main_ba2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ba_main_ba2.getIFHaveBattery()) {
					SlotNo = 2;
					nextAccordingCurrentView(ViEW_MAIN.SLOT);
				}
			}
		});
		ba_main_ba3.setNoBattery(3);
		ba_main_ba3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ba_main_ba3.getIFHaveBattery()) {
					SlotNo = 3;
					nextAccordingCurrentView(ViEW_MAIN.SLOT);
				}
			}
		});

		ba_main_ba4.setNoBattery(4);
		ba_main_ba4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ba_main_ba4.getIFHaveBattery()) {
					SlotNo = 4;
					nextAccordingCurrentView(ViEW_MAIN.SLOT);
				}
			}
		});

	}

	/**
	 * ��ʼ�����صƹ���
	 */
	private void initScreenStatus() {
		iv_main_screen.setOnClickListener(new NoDoubleClickListener() {

			@Override
			public void onNoDoubleClick(View view) {
				SlotCurrentTypeUtil.getinstance().setScreen(true);
				if (isScreenOn) {

					// notify();

					userSetLoading();

					boolean flag = BaseApplication.getBleService().send(
							mSelectedMacs,
							MyRequest.getInstance().SetScreen(
									ConCreteCmd.ISETSCREEN.SCREENOFF), true);
					BaseApplication.getLogger().debug(
							"\ntime:"
									+ MyDateUtils.getCurrentTime()
									+ "\ntype:screenoff"
									+ "\nrequest:"
									+ MyRequest.getInstance().SetScreen(
											ConCreteCmd.ISETSCREEN.SCREENOFF));
					Log.v("screen",
							"this is screenoff-------"
									+ MyRequest.getInstance().SetScreen(
											ConCreteCmd.ISETSCREEN.SCREENOFF));

				} else {

					Log.v(getTag(), "tb----isChecked");

					if (!mSelectedMacs.equals("")) {
						userSetLoading();

						boolean flag = BaseApplication.getBleService().send(
								mSelectedMacs,
								MyRequest.getInstance().SetScreen(
										ConCreteCmd.ISETSCREEN.SCREENON), true);
						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:screenon"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetScreen(
														ConCreteCmd.ISETSCREEN.SCREENON));
						Log.v("screen",
								"this is screenon--------"
										+ MyRequest
												.getInstance()
												.SetScreen(
														ConCreteCmd.ISETSCREEN.SCREENON)
										+ "");
					}

				}

			}
		});
	}

	/**
	 * ��ʼ�������
	 */

	@SuppressLint("NewApi")
	private void initSlideDrawer() {
		LayoutParams lp = (LayoutParams) slidemenu.getLayoutParams();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		lp.width = (int) ((float) dm.widthPixels * 0.618);
		slidemenu.setLayoutParams(lp);
		linear_main_slide_productverify.setOnClickListener(this);
		linear_main_slide_help.setOnClickListener(this);
		linear_main_slide_about.setOnClickListener(this);
		linear_main_slide_store.setOnClickListener(this);

	}

	/**
	 * ����ڶ�����ʱ��titlebar����
	 */
	private void initTitleBarSLot(int slotno) {
		tb_main.setBackgroundColor(getResources().getColor(R.color.titlebar));
		tb_main.setLeftImageResource(R.drawable.main_leftback);
		tb_main.setDividerColor(Color.GRAY);
		tb_main.removeAllActions();
		tb_main.setTitle("Slot" + slotno);
		tb_main.setTitleColor(getResources().getColor(R.color.WHITE));
		tb_main.setLeftClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				nextAccordingCurrentView(ViEW_MAIN.MAIN);
			}
		});

	}

	/**
	 * �������Ӽ���
	 */
	private void setDrawlister() {
		drawerLayout.setDrawerListener(new DrawerListener() {

			@Override
			public void onDrawerStateChanged(int arg0) {

			}

			@Override
			public void onDrawerSlide(View arg0, float arg1) {

			}

			@Override
			public void onDrawerOpened(View arg0) {

			}

			@Override
			public void onDrawerClosed(View arg0) {
				if (CurrentView == MAINVIEW) {
					if (GuideUtil.getMainGuide(getApplicationContext())) {
						GuideUtil.saveMainGuide(getApplicationContext(), false);
						showMainGuide();
					}
				} else if (CurrentView == SLOTVIEW) {
					if (GuideUtil.getSlotGuide(getApplicationContext())) {
						GuideUtil.saveSlotGuide(getApplicationContext(), false);
						showSlotGuide();
					}
				}

			}
		});
	}

	/**
	 * ��ʼ��titlebar һ�����湫��
	 */
	private void initTitleBarMain() {
		tb_main.setBackgroundColor(getResources().getColor(R.color.titlebar));
		tb_main.setLeftImageResource(R.drawable.main_menu);
		tb_main.setDividerColor(Color.GRAY);
		tb_main.setLeftClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				drawerLayout.openDrawer(Gravity.LEFT);
			}
		});
		tb_main.setCenterImg(R.drawable.main_titlelogo);
		tb_main.setCenterImgScale(0.9f);
		mCollectView = (ImageView) tb_main.addAction(new TitleBar.ImageAction(
				R.drawable.bluetoothoff) {
			@Override
			public void performAction(View view) {
				handler.removeMessages(1);
				nextActivity(DeviceActivity.class);

			}

		});
		if (myConstants.IFCONNECTED) {
			Log.v("test",
					"initTitleBarMain------------------------------------Cosntants.IFCONNECTED------------------------------");
			mCollectView.setImageResource(R.drawable.bluetoothon);

		}
	}

	/**
	 * ���ݵ�ǰview��Ӧ���ذ���
	 * 
	 * @param currentview
	 */
	private void exitAccordinngCurrentView(int currentview) {
		switch (currentview) {
		case ViEW_MAIN.MAIN:
			exit();
			break;
		case ViEW_MAIN.SLOT:
			nextAccordingCurrentView(ViEW_MAIN.MAIN);
			break;
		}
	}

	private long lastTime = 0;// �ṩһ����������¼��һ�ΰ��µ�ʱ��

	private void exit() {
		// �õ���ǰ��ϵͳʱ�䣨���룩
		long time = System.currentTimeMillis();
		if (time - lastTime > 2000) { // �������ʱ��̫����������2�룬�ǾͲ�Ҫ�˳�����ʾ��Ҫ�ٰ�һ��

			ToastMsg_short(R.string.main_confirm_exit);
		} else {// ��������µ�ʱ���������ڣ����˳�
			ActivityManager.getInstance().exit();
			// ����û��ǵ�һ�ΰ����򽫵�ǰ��ʱ�䱣��Ϊ��һ�ΰ���ʱ�䣬�����û��ٰ�һ�¾Ϳ����˳���

		}
		lastTime = time;
	}

	/**
	 * ������ذ���
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {// ������µ��ǻ��˽�
			// ��ʾ���»��˼��Ҳ��ǳ���
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				exitAccordinngCurrentView(CurrentView);
				// ��������д���˳�

				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * ���ݵ�ǰview����ѡ���ʼ��
	 * 
	 * @param currentview
	 */
	private void nextAccordingCurrentView(int currentview) {
		switch (currentview) {

		case ViEW_MAIN.MAIN:

			vtlist.clear();
			for (int i = 0; i < 12; i++) {
				vtlist.add(0);
			}
			dataLists.clear();
			dataLists.add(vtlist);
			dataLists.add(dataList2);
			view_percomchart_Xdate.setDataList(dataLists);
			vtcount = 0;

			CurrentView = ViEW_MAIN.MAIN;
			linear_main_second.setVisibility(View.GONE);
			sv_main_first.setVisibility(View.VISIBLE);
			r.sendmainview();
			initTitleBarMain();

			break;
		case ViEW_MAIN.SLOT:
			vtcount = 0;
			CurrentView = ViEW_MAIN.SLOT;
			linear_main_second.setVisibility(View.VISIBLE);
			initBatterySecond(this.SlotNo);
			sv_main_first.setVisibility(View.GONE);
			initTitleBarSLot(this.SlotNo);
			initSecond();

			break;
		default:
			break;
		}
	}

	/**
	 * ��ʼ���ڶ�����
	 */
	private void initSecond() {
		vtlist.clear();
		for (int i = 0; i < 12; i++) {
			vtlist.add(0);
		}
		ylist.clear();
//		for (int i = 0; i < 5; i++) {
//			ylist.add(0.0);
//		}

		r.send_time(this.SlotNo);

		initChart();
		initSlotCurrentType();
		if (GuideUtil.getSlotGuide(getApplicationContext())) {
			GuideUtil.saveSlotGuide(getApplicationContext(), false);
			showSlotGuide();
		}

	}

	/**
	 * ������Ӧͨ���û����óɹ��ĵ���ģʽ
	 * 
	 * @param imode
	 */
	public void setChoosedCurrent(int imode) {
		switch (SlotNo) {
		case 1:
			ba_main_ba1.setI_mode(imode);

			break;
		case 2:
			ba_main_ba2.setI_mode(imode);
			break;
		case 3:
			ba_main_ba3.setI_mode(imode);
			break;
		case 4:
			ba_main_ba4.setI_mode(imode);
			break;

		default:
			break;
		}

	}

	/**
	 * ��ʼ���ڶ�����������ѡ��
	 */
	private void initSlotCurrentType() {

		sct_main_second.initChoose(ba_main_second.getI_mode(),
				ba_main_second.getType(), ba_main_second.getSlotno(),
				ba_main_ba1.getAd_i(), ba_main_ba1.getMode(),
				ba_main_ba2.getAd_i(), ba_main_ba2.getMode(),
				ba_main_ba3.getAd_i(), ba_main_ba3.getMode(),
				ba_main_ba4.getAd_i(), ba_main_ba4.getMode());

		sct_main_second
				.setISlotCurrentTypeHandler(new ISlotCurrentTypeHandler() {

					@Override
					public void choose_nimh() {
						SlotCurrentTypeUtil.getinstance().setBatteryType(true,
								ConCreteCmd.ITYPE.NI_MH);
						userSetLoading();

						boolean flagnimh = BaseApplication
								.getBleService()
								.send(mSelectedMacs,
										MyRequest
												.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.NI_MH),
										true);

						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:minh"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.NI_MH));
						Log.v("choosetype",
								MyRequest.getInstance().SetBatteryTypeCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ITYPE.NI_MH));

					}

					@Override
					public void choose_nicd() {
						SlotCurrentTypeUtil.getinstance().setBatteryType(true,
								ConCreteCmd.ITYPE.NI_CD);
						userSetLoading();
						boolean flagnicd = BaseApplication
								.getBleService()
								.send(mSelectedMacs,
										MyRequest
												.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.NI_CD),
										true);
						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:micd"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.NI_CD));
						Log.v("choosetype",
								MyRequest.getInstance().SetBatteryTypeCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ITYPE.NI_CD));

					}

					@Override
					public void choose_liion() {
						SlotCurrentTypeUtil.getinstance().setBatteryType(true,
								ConCreteCmd.ITYPE.LION);
						userSetLoading();
						boolean flagliion = BaseApplication
								.getBleService()
								.send(mSelectedMacs,
										MyRequest.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.LION),
										true);
						Log.v("choosetype",
								MyRequest.getInstance().SetBatteryTypeCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ITYPE.LION));
						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:liion"
										+ "\nrequest:"
										+ MyRequest.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.LION));

					}

					@Override
					public void choose_lifepo4() {
						SlotCurrentTypeUtil.getinstance().setBatteryType(true,
								ConCreteCmd.ITYPE.LIFEPO4);
						userSetLoading();
						boolean flaglifepo4 = BaseApplication
								.getBleService()
								.send(mSelectedMacs,
										MyRequest
												.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.LIFEPO4),
										true);
						Log.v("choosetype",
								MyRequest.getInstance().SetBatteryTypeCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ITYPE.LIFEPO4));
						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:lifepo4"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetBatteryTypeCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ITYPE.LIFEPO4));

					}

					@Override
					public void choose_current200() {
						SlotCurrentTypeUtil.getinstance().setCurrent(true,
								ConCreteCmd.ICURRENT.CURRENT200);
						userSetLoading();
						boolean flag200 = BaseApplication.getBleService().send(
								mSelectedMacs,
								MyRequest.getInstance().SetChargeCurrentCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ICURRENT.CURRENT200), true);

						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:current-->2A"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT200));
						Log.v("choosecurrent",
								"flag200"
										+ flag200
										+ "this is charge request-----------------"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT200));
					}

					@Override
					public void choose_current100() {
						SlotCurrentTypeUtil.getinstance().setCurrent(true,
								ConCreteCmd.ICURRENT.CURRENT100);
						userSetLoading();
						boolean flag100 = BaseApplication.getBleService().send(
								mSelectedMacs,
								MyRequest.getInstance().SetChargeCurrentCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ICURRENT.CURRENT100), true);
						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:current-->1A"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT100));

						Log.v("choosecurrent",
								"flag100"
										+ flag100
										+ "this is charge request-----------------"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT100));
					}

					@Override
					public void choose_current050() {
						SlotCurrentTypeUtil.getinstance().setCurrent(true,
								ConCreteCmd.ICURRENT.CURRENT050);
						userSetLoading();
						boolean flag050 = BaseApplication.getBleService().send(
								mSelectedMacs,
								MyRequest.getInstance().SetChargeCurrentCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ICURRENT.CURRENT050), true);
						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:current-->500mA"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT050));

						Log.v("choosecurrent",
								"ConCreteCmd.ICURRENT.CURRENT050-------"
										+ ConCreteCmd.ICURRENT.CURRENT050
										+ "flag050------"
										+ flag050
										+ "this is charge request-----------------"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT050));
					}

					@Override
					public void choose_current025() {
						SlotCurrentTypeUtil.getinstance().setCurrent(true,
								ConCreteCmd.ICURRENT.CURRENT025);
						userSetLoading();
						boolean flag025 = BaseApplication.getBleService().send(
								mSelectedMacs,
								MyRequest.getInstance().SetChargeCurrentCmd(
										ba_main_second.getSlotno(),
										ConCreteCmd.ICURRENT.CURRENT025), true);

						BaseApplication
								.getLogger()
								.debug("\ntime:"
										+ MyDateUtils.getCurrentTime()
										+ "\ntype:current-->250mA"
										+ "\nrequest:"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT025));

						Log.v("choosecurrent",
								"flag025"
										+ flag025
										+ "this is charge request-----------------"
										+ MyRequest
												.getInstance()
												.SetChargeCurrentCmd(
														ba_main_second
																.getSlotno(),
														ConCreteCmd.ICURRENT.CURRENT025));
					}
				});

	}

	/**
	 * ���ó��ģʽ
	 * 
	 * @param mode
	 */
	private void setChargeMode(int mode) {

		switch (mode) {
		case 1:
			tb_slot_title.setText("Charging Mode:Constant-Current");
			break;
		case 2:
			tb_slot_title.setText("Charging Mode:Constant-Voltage");
			break;
		case 3:
			tb_slot_title.setText("Charging Mode:Fully Charged");
			break;
		}
	}

	/**
	 * ����slot�����Ϣ�����������ͳ��ģʽ
	 * 
	 * @param ba
	 */
	private void setCapAndChargeMode(int Cap, int mode) {
		tb_slot_chargecap.setText("Charged Capacity:" + Cap + "mAh");
		setChargeMode(mode);
	}

	/**
	 * ��ʼ���ڶ�������
	 */
	private void initBatterySecond(int no) {

		switch (no) {
		case 1:

			setCapAndChargeMode(ba_main_ba1.getCap(), ba_main_ba1.getMode());
			ba_main_second.setParam(ba_main_ba1.getSlotno(),
					ba_main_ba1.getAd_v(), ba_main_ba1.getAd_i(),
					ba_main_ba1.getI_mode(), ba_main_ba1.getMode(),
					ba_main_ba1.getTime_s(), ba_main_ba1.getCap(),
					ba_main_ba1.getType(), ba_main_ba1.getPercent());
			break;
		case 2:
			setCapAndChargeMode(ba_main_ba2.getCap(), ba_main_ba2.getMode());

			ba_main_second.setParam(ba_main_ba2.getSlotno(),
					ba_main_ba2.getAd_v(), ba_main_ba2.getAd_i(),
					ba_main_ba2.getI_mode(), ba_main_ba2.getMode(),
					ba_main_ba2.getTime_s(), ba_main_ba2.getCap(),
					ba_main_ba2.getType(), ba_main_ba2.getPercent());
			break;
		case 3:
			setCapAndChargeMode(ba_main_ba3.getCap(), ba_main_ba3.getMode());

			ba_main_second.setParam(ba_main_ba3.getSlotno(),
					ba_main_ba3.getAd_v(), ba_main_ba3.getAd_i(),
					ba_main_ba3.getI_mode(), ba_main_ba3.getMode(),
					ba_main_ba3.getTime_s(), ba_main_ba3.getCap(),
					ba_main_ba3.getType(), ba_main_ba3.getPercent());
			break;
		case 4:
			setCapAndChargeMode(ba_main_ba4.getCap(), ba_main_ba4.getMode());

			ba_main_second.setParam(ba_main_ba4.getSlotno(),
					ba_main_ba4.getAd_v(), ba_main_ba4.getAd_i(),
					ba_main_ba4.getI_mode(), ba_main_ba4.getMode(),
					ba_main_ba4.getTime_s(), ba_main_ba4.getCap(),
					ba_main_ba4.getType(), ba_main_ba4.getPercent());
			break;
		default:
			break;
		}

	}

	/**
	 * ��ʼ���ڶ�����ͼ��
	 */
	private void initChart() {
		switch (SlotNo) {
		case 1:
			ylist = InitChartXYlist.setY(ba_main_ba1.getType(), ylist);
			view_percomchart_Xdate.setYListWant(ylist);
			break;
		case 2:
			ylist = InitChartXYlist.setY(ba_main_ba2.getType(), ylist);
			view_percomchart_Xdate.setYListWant(ylist);
			break;
		case 3:
			ylist = InitChartXYlist.setY(ba_main_ba3.getType(), ylist);
			view_percomchart_Xdate.setYListWant(ylist);
			break;
		case 4:
			ylist = InitChartXYlist.setY(ba_main_ba4.getType(), ylist);
			view_percomchart_Xdate.setYListWant(ylist);
			break;

		}

		view_percomchart_Xdate.setDrawDotLine(true);
		view_percomchart_Xdate.setShowPopup(LineView.SHOW_POPUPS_NONE);
		// x zhou

		// int random = (int) (Math.random() * 180);
		// y ����
		dataList.clear();

		for (int i = 0; i < 12; i++) {
			dataList.add(10000);

		}

		// x ����

		dataList2.clear();
		InitChartXYlist.setX(dataList2);

		ArrayList<String> dataList3 = new ArrayList<String>();
		// random = (int) (Math.random() * 0);
		for (int i = 0; i < 6; i++) {
			dataList3.add(i + "");
		}

		// bottom text should set first
		view_percomchart_Xdate.setBottomTextList(dataList3);

		dataLists.add(dataList);
		dataLists.add(dataList2);
		view_percomchart_Xdate.setDataList(dataLists);

	}

	/**
	 * ��ʼ���㲥������
	 */
	private void initBroadcastReceiver() {
		mGattReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				// �˴����յĹ㲥�� MainActivity�е� mBleCallBack���׳�
				// String mac = intent
				// .getStringExtra(BaseApplication.EXTRA_DEVIE_MAC);

				if (com.quzitech.efest.constants.Action.ACTION_NOTIFY_DATA
						.equals(intent.getAction())) {
					receive_data = intent
							.getByteArrayExtra(BaseApplication.EXTRA_DATA);
					// Log.v("reponse", "reponse in the onreceive---byte--" +
					// data.toString());
					// String rxData = DataUtil.byteArrayToHex(receive_data);

					// String rxData = transferuti.bytesToHexString(data);
					// Log.v("reponse", "reponse in the onreceive-----" +
					// rxData);
					handler.obtainMessage(NOTIFY_DATA,
							DataUtil.byteArrayToHex(receive_data))
							.sendToTarget();

				} else if (com.quzitech.efest.constants.Action.ACTION_GATT_DISCONNECTED
						.equals(intent.getAction())) {
					handler.sendEmptyMessage(DISCONNECTED);
				} else if (com.quzitech.efest.constants.Action.ACTION_CONNECTED
						.equals(intent.getAction())) {
					// mCollectView.setImageResource(R.drawable.bluetoothon);
					handler.sendEmptyMessage(CONNECTED);

				} else if (com.quzitech.efest.constants.Action.ACTION_CONNECT_TIMEOUT
						.equals(intent.getAction())) {
					handler.sendEmptyMessage(CONNECT_TIMEOUT);
				}
			}
		};
	}

	/**
	 * ����ͼ�������ݲ���
	 */
	private void setIfVTEnough() {
		vtcount++;
		if (CurrentView == SLOTVIEW) {
			switch (SlotNo) {
			case 1:
				view_percomchart_Xdate.updateBottomTextList(ba_main_ba1
						.getTime_s());
				break;
			case 2:
				view_percomchart_Xdate.updateBottomTextList(ba_main_ba2
						.getTime_s());
				break;
			case 3:
				view_percomchart_Xdate.updateBottomTextList(ba_main_ba3
						.getTime_s());
				break;
			case 4:
				view_percomchart_Xdate.updateBottomTextList(ba_main_ba4
						.getTime_s());
				break;
			default:
				break;
			}

		}

		if (vtcount == 4) {
			dataLists.clear();
			dataLists.add(vtlist);
			dataLists.add(dataList2);
			view_percomchart_Xdate.setDataList(dataLists);
			vtcount = 0;
		}
	}

	/**
	 * ��ʾ������guide
	 */
	private void showMainGuide() {

		final MyDialogGuide dialogGuide1 = new MyDialogGuide(MainActivity.this);
		dialogGuide1.setImageIcon(R.drawable.main_guide1);
		dialogGuide1.setDialogGuideHandler(new IDialogGuide() {

			@Override
			public void clickpic() {
				if (!dialogGuide1.flag) {
					dialogGuide1.setImageIcon(R.drawable.main_guide2);
					dialogGuide1.flag = true;
				} else {
					dialogGuide1.dismiss();
					dialogGuide1.flag = false;
				}

			}
		});
		dialogGuide1.show();

	}

	/**
	 * ��ʾ�����Ϣ����guide
	 */
	private void showSlotGuide() {

		final MyDialogGuide dialogGuide1 = new MyDialogGuide(MainActivity.this);
		dialogGuide1.setImageIcon(R.drawable.main_slot_guide);
		dialogGuide1.setDialogGuideHandler(new IDialogGuide() {

			@Override
			public void clickpic() {

				dialogGuide1.dismiss();

			}
		});
		dialogGuide1.show();

	}

	/**
	 * ������okʱ���ã�����֮ǰ�ֶ�����ʱ�ı�ǣ�ȥ�����ֶ�������ui����
	 */
	private void setUserSetAccordingOk() {
		if (DialogUtil.instance().getIsShowing()) {

			/**
			 * 1����Ļ2�ǵ���3�ǵ������0�ǳ�����
			 */
			switch (SlotCurrentTypeUtil.getinstance().getWhichSet()) {
			case 1:
				if (isScreenOn) {
					isScreenOn = false;
					iv_main_screen
							.setImageResource(R.drawable.toggle_btn_unchecked);
				} else {
					isScreenOn = true;
					iv_main_screen
							.setImageResource(R.drawable.toggle_btn_checked);
				}
				SlotCurrentTypeUtil.getinstance().reset();
				r.sendmainview();

				break;
			case 2:
				Log.v("sleep", "i am in the case2");
				switch (SlotCurrentTypeUtil.getinstance().getWhichcurrent()) {
				case ConCreteCmd.ICURRENT.CURRENT025:
					Log.v("sleep", "i am in the CURRENT025");
					setChoosedCurrent(ConCreteCmd.ICURRENT.CURRENT025);
					sct_main_second
							.mSetCurrentType(ConCreteCmd.ICURRENT.CURRENT025);

					break;
				case ConCreteCmd.ICURRENT.CURRENT050:
					Log.v("sleep", "i am in the CURRENT050");
					setChoosedCurrent(ConCreteCmd.ICURRENT.CURRENT050);
					sct_main_second
							.mSetCurrentType(ConCreteCmd.ICURRENT.CURRENT050);

					break;
				case ConCreteCmd.ICURRENT.CURRENT100:
					Log.v("sleep", "i am in the CURRENT100");
					setChoosedCurrent(ConCreteCmd.ICURRENT.CURRENT100);
					sct_main_second
							.mSetCurrentType(ConCreteCmd.ICURRENT.CURRENT100);

					break;
				case ConCreteCmd.ICURRENT.CURRENT200:
					Log.v("sleep", "i am in the CURRENT200");
					setChoosedCurrent(ConCreteCmd.ICURRENT.CURRENT200);
					sct_main_second
							.mSetCurrentType(ConCreteCmd.ICURRENT.CURRENT200);

					break;

				default:
					break;
				}
				r.sendslot(this.SlotNo);
				break;
			case 3:
				switch (SlotCurrentTypeUtil.getinstance().getWhichtype()) {
				case ConCreteCmd.ITYPE.LION:
					sct_main_second.mSetBatteryType(ConCreteCmd.ITYPE.LION);

					ylist = InitChartXYlist.setY(ITYPE.LION, ylist);
					view_percomchart_Xdate.setYListWant(ylist);
					r.send_time(SlotNo);
					r.sendslot(this.SlotNo);
					break;
				case ConCreteCmd.ITYPE.LIFEPO4:
					sct_main_second.mSetBatteryType(ConCreteCmd.ITYPE.LIFEPO4);

					ylist = InitChartXYlist.setY(ITYPE.LIFEPO4, ylist);
					view_percomchart_Xdate.setYListWant(ylist);
					r.send_time(SlotNo);
					r.sendslot(this.SlotNo);

					break;
				case ConCreteCmd.ITYPE.NI_MH:
					sct_main_second.mSetBatteryType(ConCreteCmd.ITYPE.NI_MH);
					r.sendslot(this.SlotNo);
					break;
				case ConCreteCmd.ITYPE.NI_CD:
					sct_main_second.mSetBatteryType(ConCreteCmd.ITYPE.NI_CD);
					r.sendslot(this.SlotNo);
					break;

				default:
					break;
				}
				break;
			default:
				break;
			}
			DialogUtil.dismissDialog();
		}
	}

	/**
	 * ��̨ˢ���߳�
	 */
	private void refreshThread() {
		if (r != null) {
			switch (CurrentView) {
			case MAINVIEW:
				r.sendmainview();
				myConstants.REQUEST_FROMWHICHVIEW = MAINVIEW;
				break;
			case SLOTVIEW:

				r.sentSlotandVtTime(SlotNo);
				myConstants.REQUEST_FROMWHICHVIEW = SLOTVIEW;
				break;
			default:
				break;
			}

		}
		handler.removeMessages(TIME);
		handler.sendEmptyMessageDelayed(TIME, 10000);
	}

	/**
	 * ��ȡ���ݲ�����ˢ���߳�
	 */
	private void obtainDataThread() {
		if ((!mSelectedMacs.equals(""))
				&& BaseApplication.getBleService() != null) {
			if (r != null) {
				r.setMac(mSelectedMacs);
				// r.sendmainview();

			} else {
				r = new CmdLoopThread(BaseApplication.getBleService(),
						mSelectedMacs, getApplicationContext());
				t = new Thread(r, "CmdLoopThread");
				t.start();
			}
			handler.sendEmptyMessageDelayed(OBTAIN_DATA, 1000);
		}

	}

	/**
	 * ��֪ͨ���������Ӻ�����Ҫ��������
	 */
	private void DoWhenConnected() {
		mCollectView.setImageResource(R.drawable.bluetoothon);
		myConstants.IFCONNECTED = true;
		obtainDataThread();

	}

	/**
	 * ��֪ͨ�����ѶϿ�������Ҫ��������
	 */
	private void DoWhenDisconnected() {

		mCollectView.setImageResource(R.drawable.main_buleoff);
		myConstants.IFCONNECTED = false;

		if (CurrentView == MAINVIEW) {
			ba_main_ba1.setNoBattery(1);
			ba_main_ba2.setNoBattery(2);
			ba_main_ba3.setNoBattery(3);
			ba_main_ba4.setNoBattery(4);

		} else if (CurrentView == SLOTVIEW) {
			ba_main_second.setNoBattery(SlotNo);
		}
	}

	/**
	 * ��һ����appʱɨ��õ�����Χ����������������ϴ����ӹ��ģ����Զ�����
	 * 
	 * @param obj
	 */
	private void DoWhenDiscovery(String obj) {

		if ((obj).equals(MacUtil.getMac(getApplicationContext()))) {
			boolean flag = BaseApplication.getBleService().connect(obj, true);
			if (flag) {
				myConstants.IFCONNECTED = true;
				mSelectedMacs = MacUtil.getMac(getApplicationContext());
				if (r != null) {
					r.setMac(mSelectedMacs);

				} else {
					r = new CmdLoopThread(BaseApplication.getBleService(),
							mSelectedMacs, getApplicationContext());
					t = new Thread(r, "CmdLoopThread");
					t.start();
				}
			}
		}
	}

	/**
	 * ��ʼ��ȡ���ݸ��½��棬������Ƿ��ѽ����Զ�ˢ�£����û���򴴽��Զ�ˢ��
	 */
	private void obtainData() {
		if (myConstants.IFCONNECTED) {
			mCollectView.setImageResource(R.drawable.bluetoothon);
		} else {
			mCollectView.setImageResource(R.drawable.bluetoothoff);
		}

		r.sendmainview();
		if (!IFHAVELUNXUN) {
			IFHAVELUNXUN = true;
			handler.sendEmptyMessageDelayed(TIME, 10000);

		}

	}

	private void resLed(String obj) {
		if (StringUtil.getLocatedString(IRESTYPE.ResLED, obj) != null) {
			switch (Integer.parseInt(StringUtil.getLocatedString(
					IRESTYPE.ResLED, obj))) {
			case ResponseCmd.ISETSCREEN.SCREENON:

				iv_main_screen.setImageResource(R.drawable.toggle_btn_checked);
				isScreenOn = true;
				break;
			case ResponseCmd.ISETSCREEN.SCREENOFF:
				iv_main_screen
						.setImageResource(R.drawable.toggle_btn_unchecked);
				isScreenOn = false;

				break;
			default:
				break;
			}
		}

	}

	/**
	 * �û������󵯳�loadingҳ��,�û�����ָ���õ�����������ͣ����ص�
	 */
	private void userSetLoading() {
		DialogUtil.instance()
				.showLoadingDialog(MainActivity.this, "setting...");
		r.mSleep(1);
		handler.sendEmptyMessageDelayed(DIALOGTIMEOUT, 1500);
	}

	/**
	 * ɨ������
	 * 
	 * @param enable
	 */
	protected void scanLeDevice(final boolean enable) {
		if (enable) {
			if (BaseApplication.getBluetoothAdapter().isEnabled()) {
				if (mScanning)
					return;

				// Stops scanning after a pre-defined scan period.

				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						mScanning = false;
						BaseApplication.getBluetoothAdapter().stopLeScan(
								mLeScanCallback);
					}
				}, SCAN_PERIOD);

				mScanning = true;
				BaseApplication.getBluetoothAdapter().startLeScan(
						mLeScanCallback);

			} else {

			}
		} else {
			mScanning = false;
			BaseApplication.getBluetoothAdapter().stopLeScan(mLeScanCallback);

		}
	}

	/**
	 * ����ɨ�����
	 */
	protected BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			Log.v("test", "device.getName()" + device.getName()
					+ "device.getAddress()" + device.getAddress());
			handler.obtainMessage(DISCOVERY, device.getAddress())
					.sendToTarget();

		}
	};

	/**
	 * ��baseapplication����ж��ֻ��Ƿ�֧������4.0���ж���ᱣ��֧�ֽ����shareprefrence���
	 * ڴ˻�ȡ�ñ������� ���ݴ�����Ӧ����
	 */
	private void ifSupportBle() {
		if (IfSupUtil.getSup(getApplicationContext()).equals("2")) {

			final MyDialog dialog = new MyDialog(MainActivity.this);
			dialog.setFirstText(R.string.ble_not_supported);
			dialog.setLeftText(R.string.diolog_yes);
			dialog.setRightText(R.string.diolog_exit);

			dialog.setDialogHandler(new IDiaolgHandler() {

				@Override
				public void dialogYes(String string) {

					dialog.dismiss();
				}

				@Override
				public void dialogNo(String string) {
					ActivityManager.getInstance().exit();
					dialog.dismiss();
				}
			});
			dialog.show();

		}
	}

	/**
	 * ������������ѣ�������ת������
	 */
	private void DoWhenEsybNtf(String obj) {
		if (getBatteryReminderParamUtil.set(obj).equals("")) {
			return;
		}
		switch (Integer.parseInt(String.valueOf(getBatteryReminderParamUtil
				.set(obj).charAt(0)))) {
		case ConCreteCmd.IPASS.PASSNO1:
			switch (Integer.parseInt(String.valueOf(getBatteryReminderParamUtil
					.set(obj).charAt(1)))) {
			case ResponseCmd.IREMAINDER.FILL:
				showNotification(getResources().getString(
						R.string.main_battery1_fill));
				break;
			case ResponseCmd.IREMAINDER.REVERSER:
				ba_main_ba1.setReverse();
				break;

			}
			break;

		case ConCreteCmd.IPASS.PASSNO2:
			switch (Integer.parseInt(String.valueOf(getBatteryReminderParamUtil
					.set(obj).charAt(1)))) {
			case ResponseCmd.IREMAINDER.FILL:
				showNotification(getResources().getString(
						R.string.main_battery2_fill));
				break;
			case ResponseCmd.IREMAINDER.REVERSER:
				ba_main_ba2.setReverse();
				break;

			}
			break;
		case ConCreteCmd.IPASS.PASSNO3:
			switch (Integer.parseInt(String.valueOf(getBatteryReminderParamUtil
					.set(obj).charAt(1)))) {
			case ResponseCmd.IREMAINDER.FILL:
				showNotification(getResources().getString(
						R.string.main_battery3_fill));
				break;
			case ResponseCmd.IREMAINDER.REVERSER:
				ba_main_ba3.setReverse();
				break;

			}
			break;
		case ConCreteCmd.IPASS.PASSNO4:
			switch (Integer.parseInt(String.valueOf(getBatteryReminderParamUtil
					.set(obj).charAt(1)))) {
			case ResponseCmd.IREMAINDER.FILL:
				showNotification(getResources().getString(
						R.string.main_battery4_fill));
				break;
			case ResponseCmd.IREMAINDER.REVERSER:
				ba_main_ba4.setReverse();
				break;

			}
			break;
		}

	}

	/**
	 * ��ѯͨ����reponse�Ĵ���
	 */
	private void resQueryPass(String obj) {
		if (StringUtil.getLocatedString(IRESTYPE.ResCH, obj) != null) {
			switch (CurrentView) {
			case MAINVIEW:
				if (CurrentView == SLOTVIEW) {
					return;
				}
				switch (Integer.parseInt(String.valueOf(StringUtil
						.getLocatedString(IRESTYPE.ResCH, obj).charAt(1)))) {
				case IPASS.PASSNO1:
					if (CurrentView == SLOTVIEW) {
						return;
					}

					SetBatteryParmUtil.set(obj, ba_main_ba1);
					ba_main_ba1.updateParam();
					break;
				case IPASS.PASSNO2:
					if (CurrentView == SLOTVIEW) {
						return;
					}
					SetBatteryParmUtil.set(obj, ba_main_ba2);
					ba_main_ba2.updateParam();
					break;
				case IPASS.PASSNO3:
					if (CurrentView == SLOTVIEW) {
						return;
					}
					SetBatteryParmUtil.set(obj, ba_main_ba3);
					ba_main_ba3.updateParam();
					break;
				case IPASS.PASSNO4:
					if (CurrentView == SLOTVIEW) {
						return;
					}
					SetBatteryParmUtil.set(obj, ba_main_ba4);
					ba_main_ba4.updateParam();
					break;

				default:
					break;
				}
				break;
			case SLOTVIEW:
				if (myConstants.REQUEST_FROMWHICHVIEW == MAINVIEW) {
					break;
				} else {
					if (Integer.parseInt(String.valueOf(StringUtil
							.getLocatedString(IRESTYPE.ResCH, obj).charAt(1))) == SlotNo) {

						SetBatteryParmUtil.set(obj, ba_main_second);
						ba_main_second.updateParam();
						setCapAndChargeMode(ba_main_second.getCap(),
								ba_main_second.getMode());

					}

				}

				break;
			default:
				break;
			}

		}
	}

	/**
	 * �յ�esyb���͹���������
	 * 
	 * @param obj
	 */
	private void resNotifyData(String obj) {
		String str = HexUtil.decode(HexUtil.deleteblank(obj));
		Log.v("reponse", "reposne" + obj);
		BaseApplication.getLogger().debug(
				"\ntime:" + MyDateUtils.getCurrentTime() + "\ntype:response"

				+ "\nresponse:" + obj);
		if (MyRespose.getInstance().getResType(str) == null) {
			return;
		}
		switch (MyRespose.getInstance().getResType(str)) {

		case ResOK:
			handler.removeMessages(DIALOGTIMEOUT);
			setUserSetAccordingOk();
			ToastMsg_short("setting success!");
			Log.v("response", "response-------------->ok lalalalalaall");
			break;
		case ResLED:

			resLed(obj);

			break;
		case ResCH:
			resQueryPass(obj);

			break;
		case ResVT:
			getVTUtil.set(obj, SlotNo, vtlist);
			handler.sendEmptyMessage(IF_VT_ENOUGH);
			break;
		case ResNTF:
			DoWhenEsybNtf(obj);

			break;

		default:
			break;
		}

	}

	/**
	 * ��ʼ��handler
	 */
	private void initHandler() {

		handler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				super.dispatchMessage(msg);
				switch (msg.what) {

				case TIME:
					refreshThread();

					break;
				case IF_VT_ENOUGH:

					setIfVTEnough();

					break;
				case DISCOVERY:
					DoWhenDiscovery((String) msg.obj);

					break;
				case CONNECTED:

					DoWhenConnected();

					break;
				case DISCONNECTED:
					DoWhenDisconnected();
					break;
				case CONNECT_TIMEOUT:
					myConstants.IFCONNECTED = false;
					mCollectView.setImageResource(R.drawable.bluetoothoff);

					ToastMsg_short(R.string.device_connecttimeout);
					break;
				case OBTAIN_DATA:

					obtainData();

					break;

				case DIALOGTIMEOUT:
					if (DialogUtil.instance().getIsShowing()) {

						SlotCurrentTypeUtil.getinstance().reset();
						DialogUtil.dismissDialog();
						ToastMsg_short("setting fail!");
					}

					break;
				case NOTIFY_DATA:
					resNotifyData((String) msg.obj);
					break;
				}

			}
		};
	}

	/**
	 * ���������豸�����������豸����ҳ��ʱ��ȡ�豸mac��ַ
	 */
	private void checkConnectedDevice() {
		if (BaseApplication.getBleService() != null) {

			connectedLeDevice = null;
			mSelectedMacs = "";
			List<BluetoothDevice> connectedDevices = BaseApplication
					.getBleService().getConnectedDevices();
			if (connectedDevices != null && connectedDevices.size() == 1) {
				mSelectedMacs = (BaseApplication.getBleService()
						.getConnectedDevices().get(0).getAddress());
				Log.v(getTag(), mSelectedMacs + "--->");
				connectedLeDevice = new ConnectedLeDevice(connectedDevices.get(
						0).getName(), connectedDevices.get(0).getAddress());
				Log.v(getTag(), connectedLeDevice.toString() + "--->");
			} else {
				Log.v("ESYBMAC",
						"-connectedDevices == null || connectedDevices.size() != 1-->");
			}

		}
	}

	/**
	 * ��һ�ν���appʱ�Զ�����
	 */
	private void startConnectBack() {

		if (BaseApplication.getBleService() != null) {
			BaseApplication.getBleService().setDecode(true);

			List<BluetoothDevice> connected = BaseApplication.getBleService()
					.getConnectedDevices();
			if (connected != null && connected.size() == 0) {
				scanLeDevice(true);
			}
		}

	}

}
